import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Radio,
  Form,
  Checkbox,
  Tabs,
  message,
  Modal,
  Input,
  InputNumber,
  Table,
  Space,
  Alert,
} from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import request from '@/utils/request';
import { WhseSelect, OpMasterSelect } from '@/components/FormItemSelect';

const apiURL = '/api/services/app/Resource/';
const { TabPane } = Tabs;
const { confirm } = Modal;
const currentControl = 'Resource';

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState({ id: 0 });
  const [dataSource, setDataSource] = useState([]);
  const [defTab, setDefTab] = useState('2');
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    fetchData();
  }, []);

  const onFinish = (values: any) => {
    const { ContextData } = props;
    if (!ContextData.resourceGrpID) {
      message.error(intl.formatMessage({ id: 'pages.selectResourceGroup' }));
      return;
    }
    var model = values.Resource;
    setLoading(true);
    var act = 'Modify';
    if (model.id == 0 || !model.id) {
      act = 'New';
    }
    model.resourceGrpID = ContextData.resourceGrpID;
    model.inspPlanPartNum = '0';
    model.url = '0';
    model.calendarID = '0';
    model.burdenType = '0';
    model.assetNum = '0';
    model.linkedPart = '0';
    model.opStdID = '0';
    request(apiURL + act, {
      method: 'POST',
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          if (response.result.success) {
            message.success(intl.formatMessage({ id: 'pages.save.success' }));
            setData(response.result.data);
            fetchData();
          } else {
            message.error(response.result.message);
          }
        } else {
          message.error(response.error.message);
        }
        setLoading(false);
      }
    });
  };

  const resetForm = () => {
    formRef.current.resetFields();
    setDefTab('1');
    setData({ id: 0 });
  };

  const getData = (value: any) => {
    if (value) {
      request(apiURL + 'GetByCode', {
        method: 'GET',
        params: { code: value },
      }).then((response: any) => {
        if (response.success) {
          if (response.result.success) {
            formRef.current.setFieldsValue({ Resource: response.result.data });
            setData(response.result.data);
          } else {
            message.warning(response.result.message);
          }
        }
      });
    }
  };

  const setDataFunc = (item: any) => {
    if (item) {
      setDefTab('1');
      getData(item.resourceID);
    }
  };

  const fetchData = () => {
    request(apiURL + 'GetList', {
      method: 'GET',
    }).then((response: any) => {
      if (response && response.success) {
        var dataSource = response.result.items;
        setDataSource(dataSource);
      }
    });
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.deleteConfirm' }),
      onOk() {
        props
          .dispatch({
            type: 'Abp/delete',
            payload: { id: data.id },
            control: currentControl,
          })
          .then(() => {
            formRef.current.resetFields();
            fetchData();
            setData({ id: 0 });
          });
      },
    });
  };

  const { ContextData } = props;
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };
  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.resourceID' }),
      dataIndex: 'resourceID',
      key: 'resourceID',
    },
    {
      title: intl.formatMessage({ id: 'pages.description' }),
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: intl.formatMessage({ id: 'pages.inactive' }),
      dataIndex: 'inactive',
      key: 'inactive',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: intl.formatMessage({ id: 'pages.concurrentCapacity' }),
      dataIndex: 'concurrentCapacity',
      key: 'concurrentCapacity',
    },
    {
      title: intl.formatMessage({ id: 'pages.opCode' }),
      dataIndex: 'opCode',
      key: 'opCode',
    },
    {
      title: intl.formatMessage({ id: 'pages.dailyProdQty' }),
      dataIndex: 'dailyProdQty',
      key: 'dailyProdQty',
    },
  ];
  const filteredDataSource = dataSource.filter(
    (o: any) => o.resourceGrpID == ContextData.resourceGrpID,
  );

  return (
    <Form {...layout} ref={formRef} onFinish={onFinish}>
      <Card
        title={ContextData?.description ? ContextData?.description : '' + intl.formatMessage({ id: 'pages.resource' })}
        extra={[
          <Space key="s1">
            <Button type="primary" icon={<PlusOutlined />} onClick={resetForm}>
              {intl.formatMessage({ id: 'pages.add' })}
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              {intl.formatMessage({ id: 'pages.save' })}
            </Button>
            <Button danger onClick={delObj} disabled={data.id === 0}>
              {intl.formatMessage({ id: 'pages.delete' })}
            </Button>
          </Space>,
        ]}
      >
        <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
          <TabPane tab={intl.formatMessage({ id: 'pages.details' })} key="1">
            <Row>
              <Col span={12}>
                <Form.Item label="ID" name={['Resource', 'id']} hidden>
                  <Input />
                </Form.Item>
                <Form.Item
                  label={intl.formatMessage({ id: 'pages.resourceID' })}
                  name={['Resource', 'resourceID']}
                  rules={[{ required: true }]}
                >
                  <Input
                    onBlur={(e: any) => getData(e.target.value)}
                    style={{ width: 200 }}
                  />
                </Form.Item>
                <Form.Item label={intl.formatMessage({ id: 'pages.description' })} name={['Resource', 'description']}>
                  <Input />
                </Form.Item>
                <Form.Item label={intl.formatMessage({ id: 'pages.inputWhse' })} style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <WhseSelect
                      width={200}
                      rules={[{ required: true, message: intl.formatMessage({ id: 'pages.selectInputWhse' }) }]}
                      showSearch={false}
                      name={['Resource', 'inputWhse']}
                      placeholder={intl.formatMessage({ id: 'pages.inputWhse' })}
                    />
                    <Form.Item
                      name={['Resource', 'inputBinNum']}
                      rules={[{ required: true, message: intl.formatMessage({ id: 'pages.inputBinNum.required' }) }]}
                    >
                      <Input style={{ width: 100 }} placeholder={intl.formatMessage({ id: 'pages.binNum' })} />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item label={intl.formatMessage({ id: 'pages.outputWhse' })} style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <WhseSelect
                      width={200}
                      rules={[{ required: true, message: intl.formatMessage({ id: 'pages.selectOutputWhse' }) }]}
                      showSearch={false}
                      name={['Resource', 'outputWhse']}
                      placeholder={intl.formatMessage({ id: 'pages.outputWhse' })}
                    />
                    <Form.Item
                      name={['Resource', 'outputBinNum']}
                      rules={[{ required: true, message: intl.formatMessage({ id: 'pages.outputBinNum.required' }) }]}
                    >
                      <Input style={{ width: 100 }} placeholder={intl.formatMessage({ id: 'pages.binNum' })} />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item label={intl.formatMessage({ id: 'pages.backflushWhse' })} style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <WhseSelect
                      width={200}
                      rules={[{ required: true, message: intl.formatMessage({ id: 'pages.selectBackflushWhse' }) }]}
                      showSearch={false}
                      name={['Resource', 'backflushWhse']}
                      placeholder={intl.formatMessage({ id: 'pages.backflushWhse' })}
                    />
                    <Form.Item
                      name={['Resource', 'backflushBinNum']}
                      rules={[{ required: true, message: intl.formatMessage({ id: 'pages.backflushBinNum.required' }) }]}
                    >
                      <Input style={{ width: 100 }} placeholder={intl.formatMessage({ id: 'pages.binNum' })} />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  wrapperCol={{ offset: 5 }}
                  name={['Resource', 'inactive']}
                  valuePropName="checked"
                >
                  <Checkbox>{intl.formatMessage({ id: 'pages.inactive' })}</Checkbox>
                </Form.Item>
                <Form.Item
                  label={intl.formatMessage({ id: 'pages.resourceType' })}
                  rules={[{ required: true }]}
                  name={['Resource', 'resourceType']}
                >
                  <Radio.Group>
                    <Radio value="P">{intl.formatMessage({ id: 'pages.person' })}</Radio>
                    <Radio value="M">{intl.formatMessage({ id: 'pages.machine' })}</Radio>
                  </Radio.Group>
                </Form.Item>
                <OpMasterSelect
                  width={200}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.selectOpCode' }) }]}
                  showSearch={false}
                  name={['Resource', 'opCode']}
                  label={intl.formatMessage({ id: 'pages.opCode' })}
                />
                <Form.Item label={intl.formatMessage({ id: 'pages.queHours' })} name={['Resource', 'queHours']}>
                  <InputNumber min={0} />
                </Form.Item>
                <Form.Item
                  label={intl.formatMessage({ id: 'pages.dailyProdQty' })}
                  name={['Resource', 'dailyProdQty']}
                  rules={[{ required: true }]}
                >
                  <InputNumber min={0} />
                </Form.Item>
              </Col>
            </Row>
          </TabPane>
          <TabPane tab={intl.formatMessage({ id: 'pages.list' })} key="2">
            <Table
              rowKey="id"
              size="small"
              columns={columns}
              dataSource={filteredDataSource}
              onRow={(record) => {
                return {
                  onDoubleClick: (event) => {
                    setDataFunc(record);
                  },
                };
              }}
              footer={() => (
                <Alert message={intl.formatMessage({ id: 'pages.doubleClickToEdit' })} type="warning" showIcon closable />
              )}
            />
          </TabPane>
        </Tabs>
      </Card>
    </Form>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
